# coding:utf-8
# https://www.cnblogs.com/zhiyiYo/p/15676079.html
import os
import sys
import time

import resources.resource_rc
from PyQt5.QtCore import QRect, QRectF, QSize, Qt, QCoreApplication, pyqtSignal, QPoint, QDir, QTimer
from PyQt5.QtGui import QPainter, QPixmap, QWheelEvent, QKeySequence, QPen, QBrush, QTransform, QFont
from PyQt5.QtWidgets import (QApplication, QGraphicsItem, QGraphicsPixmapItem,
                             QGraphicsScene, QGraphicsView, QShortcut, QFileDialog, QGraphicsRectItem,
                             QGraphicsLineItem, QGraphicsSimpleTextItem)

from utils.pictureHandlers import PicturesReader

class RectTouchTestWindow(QGraphicsView):
    """ 图片查看器 """
    def __init__(self):
        super().__init__()
        self.showFullScreen()
        self.toTestDetailSignal = pyqtSignal(dict)  # 主界面的信号用来绑定子界面类的函数方法
        self.totalSet = set()
        self.doneSet = set()

        # 获取显示器分辨率
        self.desktop = QApplication.desktop()
        self.screenRect = self.desktop.screenGeometry()
        self.screenheight = self.screenRect.height()
        self.screenwidth = self.screenRect.width()
        print("Screen height {}".format(self.screenheight))
        print("Screen width {}".format(self.screenwidth))
        # 修正分辨率
        ratioL = self.screenwidth / 2560
        ratioW = self.screenheight / 1600
        print(ratioL, ratioW)
        self.screenLength = self.screenwidth
        self.screenWidth = self.screenheight
        self.rect_minRectL = int(ratioL * 80)
        self.rect_minRectW = int(ratioW * 80)
        self.rect_minOverlay = ratioW * 33

        # 快捷键
        self.screenStatus = 'Normal'
        screenShortcut = QShortcut(QKeySequence(Qt.Key_F11), self)
        screenShortcut.activated.connect(self.WindowSizeFun)
        self.setToolTip('全屏与退出全屏：\n               双击 或者 F11')
        # 测试记录
        # self.testDetailWin = TestDetailWindow()
        # self.toTestDetailSignal.connect(self.testDetailWin.RecvMainData)
        # for item in self.picturesReader.file_paths:
        #     emitData = {'status': False, "item": item, "remarks": '', 'type': 0, }
        #     self.toTestDetailSignal.emit(emitData)
        # self.testDetailWin.show()
        # 初始化小部件
        self.__initWidget()
        self.__initRectangle()
        # print('self.totalSet', len(self.totalSet))
        self.WindowSizeFun()

    def WindowSizeFun(self):
        # print(toStatus)
        if self.screenStatus == 'Normal':
            self.showFullScreen()
            self.screenStatus = 'FullScreen'
        else:
            self.showNormal()
            self.screenStatus = 'Normal'

    def __initWidget(self):
        """ 初始化小部件 """
        # self.resize(int(self.screenLength/2), int(self.screenWidth/2))
        # 隐藏滚动条
        self.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)

        # 以鼠标所在位置为锚点进行缩放
        self.setTransformationAnchor(self.AnchorUnderMouse)

        # 平滑缩放
        # self.pixmapItem.setTransformationMode(Qt.SmoothTransformation)
        self.setRenderHints(QPainter.Antialiasing |
                            QPainter.SmoothPixmapTransform)

        # 设置场景
        # self.graphicsScene.addItem(self.pixmapItem)
        # 创建场景
        self.graphicsScene = QGraphicsScene()
        self.graphicsScene.clearSelection()  # 【清除选择】
        self.setScene(self.graphicsScene)
        self.setAlignment(Qt.AlignLeft | Qt.AlignTop)
        self.setSceneRect(0, 0, self.screenLength, self.screenWidth)  # fix scene size 500 500
        self.setRenderHint(QPainter.Antialiasing)  ##设置视图的抗锯齿渲染模式。

        # 通过图标
        self.pixmapPass = QGraphicsPixmapItem(QPixmap(':/icons/icons/pass.png'))
        self.pixmapPass.setScale(0.5)
        self.pixmapPass.setZValue(1)
        self.pixmapPass.setPos(self.screenLength / 2, self.screenWidth / 2 - 100)
        self.pixmapPass.setVisible(False)
        self.graphicsScene.addItem(self.pixmapPass)

        # 首页
        self.pixmapHome = QGraphicsPixmapItem(QPixmap(':/icons/icons/home.png'))
        self.pixmapHome.setScale(0.5)
        self.pixmapHome.setZValue(1)
        self.pixmapHome.setPos(self.screenLength / 2, self.screenWidth / 2 + 200)
        self.pixmapHome.setVisible(False)
        self.pixmapHome.myName = 'home'
        self.graphicsScene.addItem(self.pixmapHome)

        # 上一项
        self.pixmapLeft = QGraphicsPixmapItem(QPixmap(':/icons/icons/left.png'))
        self.pixmapLeft.setScale(0.5)
        self.pixmapLeft.setZValue(1)
        self.pixmapLeft.setPos(self.screenLength / 2 - 300, self.screenWidth / 2 + 200)
        self.pixmapLeft.setVisible(False)
        self.pixmapLeft.myName = 'left'
        self.graphicsScene.addItem(self.pixmapLeft)

        # 下一项
        self.pixmapRight = QGraphicsPixmapItem(QPixmap(':/icons/icons/right.png'))
        self.pixmapRight.setScale(0.5)
        self.pixmapRight.setZValue(1)
        self.pixmapRight.setPos(self.screenLength / 2 + 300, self.screenWidth / 2 + 200)
        self.pixmapRight.setVisible(False)
        self.pixmapRight.myName = 'right'
        self.graphicsScene.addItem(self.pixmapRight)

        # 提示文字
        # tipText = QGraphicsSimpleTextItem('全屏与退出全屏：\n         双击 或者 F11')
        # tipText.setPen(QPen(Qt.gray))
        # tipText.setPos(int(self.screenLength / 4), int(self.screenWidth / 8))
        # tipText.setFlags(QGraphicsItem.ItemIsSelectable | QGraphicsItem.ItemIsMovable)
        # # tipText.setScale(1.5)
        # tipText.setFont(QFont(self.font().family(), 20))
        # self.graphicsScene.addItem(tipText)
        # 画对脚线
        # line1 = QGraphicsLineItem(0, 0, self.screenLength, self.screenWidth)
        # line1.setPen(QPen(Qt.gray))
        # line2 = QGraphicsLineItem(0, self.screenWidth, self.screenLength, 0)
        # line2.setPen(QPen(Qt.gray))
        # rect.setBrush(QBrush(Qt.blue))
        # 加入场景
        # self.graphicsScene.addItem(line1)
        # self.graphicsScene.addItem(line2)

    def __initRectangle(self):
        # print('__initRectangle', self.rect_minRectL)
        # 画长方形
        # xy – 定义边界框，[(x0, y0), (x1, y1)] or [x0, y0, x1, y1],
        # outline – 轮廓线条颜色
        # fill – 填充颜色
        # width – 线条宽度，单位 pixels

        ## 画对角线
        coordListX = range(0, self.screenLength, self.rect_minRectL)
        coordListY = range(0, self.screenWidth, self.rect_minRectW)
        for i in range(len(coordListX)):
            drawFlag = True
            for j in range(len(coordListY)):
                if i == 0 and j == 0:
                    drawFlag = False
                elif i == (len(coordListX) - 1):
                    continue
                # elif i == (len(coordListX)/2 - 1):
                #     continue
                if drawFlag:
                    rect = QGraphicsRectItem(i * self.rect_minRectL,
                                             i * self.rect_minRectW - (i - 1) * self.rect_minOverlay,
                                             self.rect_minRectL, self.rect_minRectW)
                    rect.setPen(QPen(Qt.blue))
                    # rect.setBrush(QBrush(Qt.blue))
                    self.graphicsScene.addItem(rect)
                    self.totalSet.add(rect)
                    itemX = int(i * self.rect_minRectL)
                    itemY = int(self.screenWidth - (i + 1) * self.rect_minRectW + (
                            i - 1) * self.rect_minOverlay)
                    if self.itemAt(itemX + 5, itemY):
                        itemY = itemY + self.rect_minOverlay
                    elif self.itemAt(itemX + 5, itemY + self.rect_minRectW):
                        itemY = itemY - self.rect_minOverlay
                    # 加入场景
                    rect2 = QGraphicsRectItem(itemX, itemY, self.rect_minRectL,
                                              self.rect_minRectW)
                    rect2.setPen(QPen(Qt.blue))
                    self.graphicsScene.addItem(rect2)
                    self.totalSet.add(rect2)
                    drawFlag = False

        ## 四边
        for dX in coordListX:
            for dY in coordListY:
                drawFlag = False
                # print(dX, dY)
                if dX == 0:
                    drawFlag = True
                if dX != 0 and dY == 0:
                    drawFlag = True
                if dX == self.screenLength - self.rect_minRectL and dY != 0:
                    drawFlag = True
                if self.screenWidth - self.rect_minRectW == dY and dX != 0 and dX != self.screenLength - self.rect_minRectL:
                    drawFlag = True
                if drawFlag:
                    rect = QGraphicsRectItem(dX, dY, self.rect_minRectL, self.rect_minRectW)
                    rect.setPen(QPen(Qt.blue))
                    # rect.setBrush(QBrush(Qt.blue))
                    # 加入场景
                    self.graphicsScene.addItem(rect)
                    self.totalSet.add(rect)

    # def DrawRectFun(self, rectX=0, rectY=0):
    def mousePressEvent(self, evt):
        self.item = self.get_item_at_click(evt)
        pt = evt.pos()  # 获取鼠标坐标--view坐标
        QGraphicsView.mousePressEvent(self, evt)
        if self.item is not None:
            # print('self.item: ', self.item)
            try:
                myName = self.item.myName
                if 'home' in myName:
                    # print('home')
                    self.close()
                elif 'left' in myName:
                    # print('left')
                    # self.picturesPlayWin.show()
                    # self.picturesPlayWin.showFullScreen()
                    self.close()
                elif 'right' in myName:
                    # print('right')
                    # self.myConfig.gyroWin.show()
                    # self.gyroWin.showFullScreen()
                    self.close()
            except Exception as e:
                pass
                # print('Error:', e)
            # self.flag = True

    #         print('self.item: ', self.item)
    #         self.pixmapPass.setVisible(True)
    #         self.timeoutTimer.start(1000)
    #         # self.item.setPen(QPen(Qt.red))
    #         self.item.setBrush(QBrush(Qt.red))
    #     else:
    #         # self.flag = False
    #         print('self.item is None')
    # viewW, viewH = self.rect().width(), self.rect().height()
    # viewCoordX, viewCoordY = QPoint(pt).x(), QPoint(pt).y(),  # 转为QPoint可提取X,Y值
    # if viewCoordY < viewH / 4:
    #     print('单击上边，全屏', viewW, viewH)
    #     self.WindowSizeFun(toStatus='FullScreen')
    # elif viewCoordY > viewH * 3 / 4:
    #     print('单击下边，推出全屏', viewW, viewH)
    #     self.WindowSizeFun(toStatus='Normal')
    # ptscene = self.mapToScene(pt)  # 把view坐标转换为场景坐标
    # self.x1 = ptscene.x()
    # self.y1 = ptscene.y()
    # print('x1:', self.x1, 'y1', self.y1)
    # self.x1 = pt.x()
    # self.y1 = pt.y()

    def mouseDoubleClickEvent(self, event):
        # point = self.mapToScene(event.pos())
        # item = self.graphicsScene.itemAt(point, QTransform())
        # self.graphicsScene.removeItem(item)
        self.WindowSizeFun()
        super().mouseDoubleClickEvent(event)
        # print(len(self.doneSet), self.doneSet)

    def mouseMoveEvent(self, evt):
        pt = evt.pos()  # 获取鼠标坐标--view坐标
        QGraphicsView.mouseMoveEvent(self, evt)
        # print('view坐标:{},{}'.format(pt.x(), pt.y()))
        # ptscene = self.mapToScene(pt)  # 把view坐标转换为场景坐标
        # self.x_real = ptscene.x()
        # self.y_real = ptscene.y()
        # print('scene坐标:{:.0f},{:.0f}'.format(ptscene.x(), ptscene.y()))
        # item = self.graphicsScene.itemAt(ptscene, self.transform())  # 在场景某点寻找图元--最上面的图元\
        self.item = self.get_item_at_click(evt)
        # 返回值：图元地址
        # 参数1 场景点坐标
        # 参数2 ？？？？
        if self.item != None:
            # self.pixmapPass.setVisible(True)
            # self.timeoutTimer.start(1000)
            # self.item.setPen(QPen(Qt.red))
            try:
                self.item.setBrush(QBrush(Qt.red))
                self.doneSet.add(self.item)
                # print(len(self.doneSet), len(self.totalSet))
                if len(self.totalSet) >= 160 and len(self.totalSet ^ self.doneSet) == 0:
                    # print('ok' * 20)
                    self.pixmapPass.setVisible(True)
                    self.pixmapHome.setVisible(True)
                    self.pixmapLeft.setVisible(True)
                    self.pixmapRight.setVisible(True)
                    self.passItems.append('RectTouchTest')
            except Exception as e:
                pass
                # print('Error:', e)
            # ptitem = item.mapFromScene(ptscene)  # 把场景坐标转换为图元坐标
            # print('item坐标:{:.0f},{:.0f}'.format(ptitem.x(), ptitem.y()))

    #         # 这里可以设旗子
    #         edge = Edge(self.scene, [self.x1, self.y1], [self.x_real, self.y_real])
    #         edge.repaint(self.x1, self.y1, self.x_real, self.y_real)
    #     # if not self.view.flag:
    #     #     edge = Edge(self.scene, [self.x1, self.y1], [self.x_real, self.y_real])
    #     # edge.repaint(self.x1, self.y1, self.x_real, self.y_real)

    # def mouseReleaseEvent(self, evt):
    #     pt = evt.pos()  # 获取鼠标坐标--view坐标
    #     QGraphicsView.mouseReleaseEvent(self, evt)
    #     ptscene = self.mapToScene(pt)  # 把view坐标转换为场景坐标
    #
    #     self.x2 = ptscene.x()
    #     self.y2 = ptscene.y()
    #     print('x2:', self.x2, 'y2', self.y2)
    def get_item_at_click(self, e):
        pos = e.pos()
        item = self.itemAt(pos)
        return item


if __name__ == '__main__':
    QCoreApplication.setAttribute(Qt.AA_EnableHighDpiScaling)
    app = QApplication(sys.argv)
    w = RectTouchTestWindow()
    w.show()
    # w.showFullScreen()
    sys.exit(app.exec_())
